//
//  Generics.swift
//  a_swift_tour
//
//  Created by yao_yu on 14-8-18.
//  Copyright (c) 2014年 yao_yu. All rights reserved.
//

import Foundation

func GenericsTest(){
    var a = repeat("knock", 4)
    //println(a)        // [knock, knock, knock, knock]
    
    var possibleInteger:OptionalValue<Int> = .None
    possibleInteger = .Some(100)
    
    var res = anyCommonElements([1,2,3], [30])
    println(res)
}

//P47 通用编程
func repeat<T>(item:T, times:Int) ->[T]{
    var result = [T]()
    for i in 0..<times{
        result.append(item)
    }
    return result
}

// P48 Swift标准库optional类型实现
enum OptionalValue<T>{
    case None
    case Some(T)
}

// P49
func anyCommonElements<T,U where T:SequenceType, U:SequenceType, T.Generator.Element:Equatable, T.Generator.Element == U.Generator.Element>(lhs:T, rhs:U) -> Bool{
    for lhsItem in lhs{
        for rhsItem in rhs{
            if lhsItem == rhsItem{
                return true
            }
        }
    }
    return false
}

// P49
func anyCommonElements3<T where T.Generator.Element:Equatable, T:SequenceType>(lhs:T, rhs:T) -> Bool{
    for lhsItem in lhs{
        for rhsItem in rhs{
            if lhsItem == rhsItem{
                return true
            }
        }
    }
    return false
}

// 泛型处理, 返回数组
func anyCommonElements<T:Equatable>(lhs:[T], rhs:[T]) -> [T]{
    var res = [T]()
    for lhsItem in lhs{
        for rhsItem in rhs{
            if lhsItem == rhsItem{
                res.append(lhsItem)
            }
        }
    }
    return res
}
